package com.shouhuobao.bhi.loc;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.ZoomControls;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapStatusChangeListener;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.collectplus.express.BaseActivity;
import com.collectplus.express.R;
import com.collectplus.express.tools.Umeng;
import com.collectplus.express.view.DeleteEditText;

import java.util.ArrayList;

import droid.frame.activity.title.TitleRes;
import droid.frame.utils.android.ImmUtils;
import droid.frame.utils.android.Log;

/**
 * 定位
 *
 * @author coffee<br>
 * 2015-8-3下午3:56:10
 */
public class LocationActivity extends BaseActivity implements OnClickListener, OnGetGeoCoderResultListener, OnGetPoiSearchResultListener {

    private final String TAG = "ChangeAddressActivity";

    private RelativeLayout mTitleLayout;
    private ListView mListView, mSearchListView;

    private DeleteEditText mEditText;// 搜索输入框
    private Button mEditCancelButton;// 取消搜索
    private ImageView mCurrentAddressIcon, mCenterIcon;

    private ArrayList<PoiInfo> mList = new ArrayList<PoiInfo>();
    private ChangeAddressAdapter mAdapter;

    private ArrayList<PoiInfo> mSearchList;
    private ChangeAddressAdapter mSearchAdapter;

    private String mCity;
    // 定位相关
    private LocationClient mLocClient;
    private GeoCoder mSearch;
    private PoiSearch mPoiSearch;
    private MyLocationListenner myListener = new MyLocationListenner();
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    boolean isFirstLoc = true;// 是否首次定位
    private BDLocation mCurrentLocation;

    private boolean isSelect = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getIntent().getStringExtra("city") != null) {
            mCity = getIntent().getStringExtra("city");
        } else {
            mCity = "北京";
        }

        // 初始化搜索模块，注册事件监听
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(this);

        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(this);
        Log.d("location-", "onCreate - end");
    }

    private void startCenterIconAnimation() {
        mCenterIcon.setVisibility(View.VISIBLE);
        TranslateAnimation translateAnimation = new TranslateAnimation(0, 0, -450, 0);
        // // 动画集
        AnimationSet set = new AnimationSet(true);
        set.addAnimation(translateAnimation);
        set.setFillAfter(true);

        // 设置动画时间 (作用到每个动画)
        set.setDuration(600);
        mCenterIcon.startAnimation(set);
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.address_change);
        super.findViewById();
        setCommonTitle("选择上门地址", new TitleRes(0, "下一步", new View.OnClickListener() {
            public void onClick(View v) {
                Intent i = new Intent(LocationActivity.this, LocationSaveActivity.class);
                if (mAdapter == null) {
                    return;
                }
                PoiInfo poi = mList.get(mAdapter.getSlect());
                i.putExtra("name", poi.name);
                i.putExtra("address", poi.address);
                i.putExtra("latitude", poi.location.latitude);
                i.putExtra("longitude", poi.location.longitude);
                startActivityForResult(i, 100);
            }
        }));
        Log.d("location-", "onCreate - findviewById -- 000");
        mTitleLayout = (RelativeLayout) findViewById(R.id.app_title_layout);
        mEditCancelButton = (Button) findViewById(R.id.change_address_edit_cancel);
        mEditCancelButton.setOnClickListener(this);
        mEditText = (DeleteEditText) findViewById(R.id.change_address_edit);
        Log.d("location-", "onCreate - findviewById -- 1");
        //
        mEditText.clearFocus();
        mEditText.setFocusable(false);
        mEditText.setOnClickListener(this);

        Log.d("location-", "onCreate - findviewById -- 2");
        mEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 0) {
                    if (mSearchList != null) {
                        mSearchList.clear();
                    }
                    return;
                }
                mPoiSearch.searchInCity((new PoiCitySearchOption()).city(mCity) //
                        .keyword(mEditText.getText().toString()).pageNum(1).pageCapacity(20));
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        Log.d("location-", "onCreate - findviewById -- 3");
        mListView = (ListView) findViewById(R.id.listview);
        mListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                mAdapter.setSelect(position);
                mAdapter.notifyDataSetChanged();

                PoiInfo poi = (PoiInfo) mAdapter.getItem(position);
                LatLng ll = new LatLng(poi.location.latitude, poi.location.longitude);
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                mBaiduMap.animateMapStatus(u);
                isSelect = true;
            }
        });
        mSearchListView = (ListView) findViewById(R.id.change_address_search_listview);
        mSearchListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                PoiInfo poi = (PoiInfo) mSearchAdapter.getItem(position);
                LatLng ll = new LatLng(poi.location.latitude, poi.location.longitude);
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                mBaiduMap.animateMapStatus(u);
                //
                mEditCancelButton.setTag(position);
                onClick(mEditCancelButton);
            }
        });
        Log.d("location-", "onCreate - findviewById -- 4");
        mCurrentAddressIcon = (ImageView) findViewById(R.id.change_address_map_to_current);
        mCurrentAddressIcon.setOnClickListener(this);
        mCenterIcon = (ImageView) findViewById(R.id.change_address_map_center_icon);
        mCenterIcon.setOnClickListener(this);
        Log.d("location-", "onCreate - initMapView - start");
        initMapView();
        Log.d("location-", "onCreate - initMapView - end");
    }

    private void initMapView() {
        // 地图初始化
        mMapView = (MapView) findViewById(R.id.bmapView);
        int count = mMapView.getChildCount();
        for (int i = 0; i < count; i++) {
            View child = mMapView.getChildAt(i);
            // 隐藏缩放按键 ZoomControl
            if (child instanceof ImageView || child instanceof ZoomControls) {
                child.setVisibility(View.INVISIBLE);
            }
        }
        mBaiduMap = mMapView.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 定位初始化
        mLocClient = new LocationClient(getContext());
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
        option.setIsNeedAddress(true);
        mLocClient.setLocOption(option);
        mLocClient.start();

        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(18.0f);
        mBaiduMap.setMapStatus(msu);
        mBaiduMap.setOnMapStatusChangeListener(new OnMapStatusChangeListener() {

            @Override
            public void onMapStatusChangeStart(MapStatus status) {

            }

            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

            }

            @Override
            public void onMapStatusChangeFinish(MapStatus status) {
                if (!isSelect) {
                    startGetGeo(status.target.latitude, status.target.longitude);
                } else {
                    isSelect = false;
                }
            }

            @Override
            public void onMapStatusChange(MapStatus status) {

            }
        });
    }

    private void startGetGeo(double latitude, double longitude) {
        LatLng ptCenter = new LatLng(latitude, longitude);
        mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(ptCenter));
    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult arg0) {
    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(LocationActivity.this, "抱歉，未能找到结果", Toast.LENGTH_LONG).show();
            return;
        }
        mList.clear();
        PoiInfo poiInfo = new PoiInfo();
        poiInfo.name = "当前位置";
        poiInfo.address = result.getAddress();
        poiInfo.location = result.getLocation();
        mList.add(poiInfo);
        if (result.getPoiList() != null) {
            mList.addAll(1, result.getPoiList());
        }
        // mList = result.getPoiList();
        if (mList != null && mList.size() > 0) {
            mAdapter = new ChangeAddressAdapter(LocationActivity.this, mList);
            mAdapter.setSelect(0);
            mListView.setAdapter(mAdapter);
        }
    }

    @Override
    public void onGetPoiDetailResult(PoiDetailResult arg0) {

    }

    @Override
    public void onGetPoiResult(PoiResult result) {
        if (result == null || result.getAllPoi() == null || result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
            if (mSearchListView != null) {
                mSearchListView.setAdapter(null);
            }
            showToast("搜索结果为空");
            return;
        }
        if (mSearchList == null) {
            mSearchList = new ArrayList<PoiInfo>();
        }
        mSearchList.clear();
        mSearchList.addAll(result.getAllPoi());
        //
        mSearchAdapter = new ChangeAddressAdapter(LocationActivity.this, mSearchList);
        mSearchListView.setAdapter(mSearchAdapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Umeng.onResume(TAG, this);
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Umeng.onPause(TAG, this);
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        mMapView.onDestroy();
        mSearch.destroy();
        mPoiSearch.destroy();
        mLocClient.unRegisterLocationListener(myListener);
        mLocClient.stop();// TODO 记得关闭
        mMapView = null;
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100 && RESULT_OK == resultCode) {
            setResult(RESULT_OK, data);
            finish();
        }
    }

    /**
     * 定位SDK监听函数
     */
    private class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            try {
                MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius())
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(100).latitude(location.getLatitude()).longitude(location.getLongitude()).build();
                mBaiduMap.setMyLocationData(locData);
                if (isFirstLoc) {
                    isFirstLoc = false;
                    LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
                    MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                    mBaiduMap.animateMapStatus(u);
                    startCenterIconAnimation();
                    //
                    startGetGeo(location.getLatitude(), location.getLongitude());
                }
                mCurrentLocation = location;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 编辑框单击事件
            case R.id.change_address_edit:
                if ("search".equals(v.getTag())) {
                    return;
                }
                v.setTag("search"); // 设置为搜索模式
                //
                if (mSearchList != null) {
                    mSearchList.clear();
                }
                mSearchAdapter = null;
                mSearchListView.setAdapter(mSearchAdapter);
                mEditCancelButton.setVisibility(View.VISIBLE);
                mSearchListView.setVisibility(View.VISIBLE);
                mTitleLayout.setVisibility(View.GONE);
                //
                getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mEditText.setFocusable(true);
                        mEditText.setFocusableInTouchMode(true);
                        mEditText.requestFocus();
                        ImmUtils.show(getContext(), mEditText);
                    }
                }, 500);
                break;
            case R.id.change_address_edit_cancel:
                mEditCancelButton.setVisibility(View.GONE);
                ImmUtils.hide(getContext());
                mSearchListView.setVisibility(View.GONE);
                mTitleLayout.setVisibility(View.VISIBLE);
                mEditText.setText(null);
                mEditText.setTag(null); // 设置为搜索模式
                mEditText.setFocusable(false);
                mEditText.clearFocus();
                // int position = Integer.valueOf(v.getTag() + "");
                // mListView.setSelection(position + 1);
                break;
            case R.id.change_address_map_to_current:
                LatLng ll = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                mBaiduMap.animateMapStatus(u);
                break;
        }
    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult arg0) {

    }

}
